#include "mainwindow.h"
#include "ui_mainwindow.h"
//构造函数
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , model(new QStandardItemModel(this)) // 初始化模型
{
    ui->setupUi(this);
    ui->List->setModel(model);

    //槽函数集合
    connect(ui->List, &QListView::clicked, this, &MainWindow::onSelected);
    connect(ui->Connect, &QPushButton::clicked, this, &MainWindow::onConnectDatabases);

    connect(ui->NewBook, &QPushButton::clicked, this, &MainWindow::NewBook);
    connect(ui->NewOrder, &QPushButton::clicked, this, &MainWindow::NewOrder);
    connect(ui->NewStore, &QPushButton::clicked, this, &MainWindow::NewStore);
    connect(ui->NewClient, &QPushButton::clicked, this, &MainWindow::NewClient);
    connect(ui->intoSave, &QPushButton::clicked, this, &MainWindow::NewSave);
    connect(ui->NewSend, &QPushButton::clicked, this, &MainWindow::NewSend);
    connect(ui->Help, &QPushButton::clicked, this, &MainWindow::NewHelp);
    connect(ui->About, &QPushButton::clicked, this, &MainWindow::NewAbout);

    connect(ui->BookList, &QPushButton::clicked, this, &MainWindow::refBookList);
    connect(ui->ClientList, &QPushButton::clicked, this, &MainWindow::refClientList);
    connect(ui->BuyList, &QPushButton::clicked, this, &MainWindow::refBuyList);
    connect(ui->OrderList, &QPushButton::clicked, this, &MainWindow::refOrderList);
    connect(ui->SaveList, &QPushButton::clicked, this, &MainWindow::refSaveList);
    connect(ui->SendList, &QPushButton::clicked, this, &MainWindow::refSendList);
    connect(ui->StoreList, &QPushButton::clicked, this, &MainWindow::refStoreList);

    connect(ui->SearchEdit, &QLineEdit::editingFinished, this, &MainWindow::SearchShow);

    connect(ui->DelSelect, &QPushButton::clicked, this, &MainWindow::delSelect);

    connect(ui->quit, &QPushButton::clicked, this, &MainWindow::close);

    //处理模型
    infoModel = new QStandardItemModel(this);
    ui->Information->setModel(infoModel);
}
//析构函数
MainWindow::~MainWindow()
{
    onDisConnectDatabases();
    delete ui;
}
//连接数据库
QString connName = "qt_sql_default_connection";

void MainWindow::onConnectDatabases()
{
    if (QSqlDatabase::contains(connName)) {
        onDisConnectDatabases(); // 彻底释放
    }
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", connName);
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setDatabaseName("Ivan");
    db.setUserName("root");
    db.setPassword("215108");

    if (db.open()) {
        // 重新创建模型并绑定
        model = new QStandardItemModel(this);
        infoModel = new QStandardItemModel(this);
        ui->List->setModel(model);
        ui->Information->setModel(infoModel);
        QMessageBox::information(this, "成功", "数据库连接成功");
    } else {
        QMessageBox::critical(this, "错误", "数据库连接失败");
    }
}

//断开数据库
void MainWindow::onDisConnectDatabases()
{
    //断开所有 view 的 model
    ui->List->setModel(nullptr);
    ui->Information->setModel(nullptr);

    //主动释放模型对象
    delete model;
    model = nullptr;
    delete infoModel;
    infoModel = nullptr;

    //关闭并移除数据库
    if (QSqlDatabase::contains(connName)) {
        QSqlDatabase db = QSqlDatabase::database(connName);
        if (db.isOpen()) db.close();
        QSqlDatabase::removeDatabase(connName);
    }
}

//刷新左侧列表
void MainWindow::refBookList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "BookList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM BookList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refClientList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "ClientList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM ClientList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refBuyList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "BuyList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM BuyList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refOrderList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "OrderList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM OrderList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refSaveList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "SaveList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM SaveList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refSendList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "SendList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM SendList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}

void MainWindow::refStoreList()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    currentTable = "StoreList";
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    if (query.exec("SELECT * FROM StoreList")) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
    } else {
        QMessageBox::warning(this, "Error", "查询失败！");
    }
}


void MainWindow::NewBook()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    nbook = new Nbook(this);  // 创建新的Nbook窗口实例
    nbook->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(nbook, &QDialog::finished, this, &MainWindow::refBuyList);//刷新
    nbook->show();  // 显示窗口
}

void MainWindow::NewOrder()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    norder = new class norder(this);  // 窗口实例
    norder->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(norder, &QDialog::finished, this, &MainWindow::refOrderList);//刷新
    norder->show();  // 显示窗口
}

void MainWindow::NewStore()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    nstore = new class nstore(this);  // 创建新的窗口实例
    nstore->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(nstore, &QDialog::finished, this, &MainWindow::refStoreList);//刷新
    nstore->show();  // 显示窗口
}

void MainWindow::NewClient()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    nclient = new class nclient(this);  // 创建新的窗口实例
    nclient->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(nclient, &QDialog::finished, this, &MainWindow::refClientList);//刷新
    nclient->show();  // 显示窗口
}

void MainWindow::NewSave()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    ibook = new class ibook(this);  // 窗口实例
    ibook->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(ibook, &QDialog::finished, this, &MainWindow::refSaveList);//刷新
    ibook->show();  // 显示窗口
}

void MainWindow::NewSend()
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    sendok = new class sendok(this);  // 窗口实例
    sendok->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    connect(sendok, &QDialog::finished, this, &MainWindow::refSendList);//刷新
    sendok->show();  // 显示窗口
}

void MainWindow::NewHelp()
{
    help = new class help(this);  // 窗口实例
    help->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    help->show();  // 显示窗口
}

void MainWindow::NewAbout()
{
    about = new class about(this);  // 窗口实例
    about->setAttribute(Qt::WA_DeleteOnClose);  // 关闭时自动删除实例
    about->show();  // 显示窗口
}

void MainWindow::onSelected(const QModelIndex &index) //右：来自左
{
    QSqlDatabase db = QSqlDatabase::database(connName);
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }
    if (!model || !infoModel) {
        QMessageBox::warning(this, "警告", "模型未初始化！");
        return;
    }
    QString selectedName = model->data(index, Qt::DisplayRole).toString();
    infoModel->clear();

    QSqlQuery query(db);

    if (currentTable == "BookList") key = "Bname";
    else if (currentTable == "ClientList") key = "ClientID";
    else if (currentTable == "BuyList") key = "BookID";
    else if (currentTable == "OrderList") key = "OrderID";
    else if (currentTable == "SaveList") key = "SaveID";
    else if (currentTable == "SendList") key = "SendID";
    else if (currentTable == "StoreList") key = "StoreID";
    else {
        QMessageBox::warning(this, "警告", "未知的表名！");
        return;
    }

    QString lang = QString("SELECT * FROM %1 WHERE %2 = ?")
                       .arg(currentTable)
                       .arg(key);
    query.prepare(lang);
    query.addBindValue(selectedName);

    if (!query.exec()) {
        QMessageBox::critical(this, "SQL错误", "错误");
        return;
    }
    if (query.next()) {
        infoModel->setHorizontalHeaderLabels({"属性", "内容"});
        QSqlRecord record = query.record();
        for (int i = 0; i < record.count(); ++i) {
            QString fieldName = record.fieldName(i);
            QString fieldValue = query.value(i).toString();
            infoModel->appendRow({
                new QStandardItem(fieldName),
                new QStandardItem(fieldValue),
            });
        }
    }
}

void MainWindow::delSelect() {
    QModelIndex currentIndex = ui->List->currentIndex();
    if (!currentIndex.isValid()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的项！");
        return;
    }

    QString selectedName = model->data(currentIndex, Qt::DisplayRole).toString();

    // 添加确认对话框
    if (QMessageBox::question(this, "确认",
                              QString("确定要删除 %1 吗？").arg(selectedName),
                              QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
        return;
    }

    QSqlDatabase db = QSqlDatabase::database(connName);
    QSqlQuery query(db);

    QString lang = QString("DELETE FROM %1 WHERE %2 = ?")
                       .arg(currentTable)
                       .arg(key);

    query.prepare(lang);
    query.addBindValue(selectedName);

    if (!query.exec()) {
        QMessageBox::critical(this, "SQL错误",
                              QString("删除失败"));
        return;
    }

    QMessageBox::information(this, "成功", "删除成功！");

    // 刷新列表显示
    if (currentTable == "BookList") refBookList();
    else if (currentTable == "ClientList") refClientList();
    else if (currentTable == "BuyList") refBuyList();
    else if (currentTable == "OrderList") refOrderList();
    else if (currentTable == "SaveList") refSaveList();
    else if (currentTable == "SendList") refSendList();
    else if (currentTable == "StoreList") refStoreList();
}

void MainWindow::SearchShow() {
    QString searchText = ui->SearchEdit->text().trimmed();
    QSqlDatabase db = QSqlDatabase::database(connName);
    
    if (!db.isOpen()) {
        QMessageBox::warning(this, "警告", "数据库未连接！");
        return;
    }

    if (currentTable.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要搜索的列表！");
        return;
    }

    // 如果搜索框为空，则显示所有数据
    if (searchText.isEmpty()) {
        if (currentTable == "BookList") refBookList();
        else if (currentTable == "ClientList") refClientList();
        else if (currentTable == "BuyList") refBuyList();
        else if (currentTable == "OrderList") refOrderList();
        else if (currentTable == "SaveList") refSaveList();
        else if (currentTable == "SendList") refSendList();
        else if (currentTable == "StoreList") refStoreList();
        return;
    }

    // 获取当前表的查询字段
    if (currentTable == "BookList") key = "Bname";
    else if (currentTable == "ClientList") key = "ClientID";
    else if (currentTable == "BuyList") key = "BookID";
    else if (currentTable == "OrderList") key = "OrderID";
    else if (currentTable == "SaveList") key = "SaveID";
    else if (currentTable == "SendList") key = "SendID";
    else if (currentTable == "StoreList") key = "StoreID";
    else {
        QMessageBox::warning(this, "警告", "未知的表名！");
        return;
    }

    QSqlQuery query(db);
    model->clear();

    QString sql = QString("SELECT * FROM %1 WHERE %2 LIKE ?")
                     .arg(currentTable)
                     .arg(key);
    
    query.prepare(sql);
    query.addBindValue("%" + searchText + "%");

    if (query.exec()) {
        while (query.next()) {
            QStandardItem *item = new QStandardItem(query.value(0).toString());
            model->appendRow(item);
        }
        
        if (model->rowCount() == 0) {
            QMessageBox::information(this, "提示", "没有找到匹配的结果");
        }
    } else {
        QMessageBox::warning(this, "错误", "搜索失败");
    }
}
